<!DOCTYPE html>
<html>
  <head>
    <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
    <script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.min.js"></script>
  </head>
  <body style="margin: 0px; overflow: hidden">
    <a-scene embedded arjs>
      <a-marker preset="hiro">
        <a-entity position="0 0 0">
          <!-- 创建一个平面 -->
          <a-plane
            position="0 0 0"
            rotation="-90 0 0"
            width="1"
            height="1"
            color="#DDDDDD"
          ></a-plane>

          <!-- 创建一个用于测量距离的线段 -->
          <a-entity
            id="distanceLine"
            line="start: 0 0 0; end: 0 0 -1; color: red;"
          ></a-entity>

          <!-- 创建一个用于测量面积的多边形 -->
          <a-entity id="areaPolygon" line="color: blue;"></a-entity>
        </a-entity>
      </a-marker>
      <a-camera-static></a-camera-static>
    </a-scene>

    <script>
      // 获取marker对象
      const marker = document.querySelector("a-marker");

      // 获取线段和多边形对象
      const distanceLine = document.querySelector("#distanceLine");
      const areaPolygon = document.querySelector("#areaPolygon");

      // 初始化测量数据
      let startPoint = null;
      let endPoint = null;
      let polygonPoints = [];

      // 监听marker的点击事件
      marker.addEventListener("click", function () {
        if (!startPoint) {
          // 第一个点，设置为起点
          startPoint = marker.object3D.position.clone();
        } else if (startPoint && !endPoint) {
          // 第二个点，设置为终点，并进行距离测量
          endPoint = marker.object3D.position.clone();

          const distance = startPoint.distanceTo(endPoint);
          distanceLine.setAttribute(
            "line",
            `start: ${startPoint.x} ${startPoint.y} ${startPoint.z}; end: ${endPoint.x} ${endPoint.y} ${endPoint.z}`
          );
          alert(`距离为：${distance.toFixed(2)} 米`);

          // 重置测量数据
          startPoint = null;
          endPoint = null;
        } else {
          // 第三个及以后的点，用于面积测量
          const point = marker.object3D.position.clone();
          polygonPoints.push(point);

          if (polygonPoints.length > 1) {
            // 更新多边形的线段
            let lineSegments = "";
            for (let i = 0; i < polygonPoints.length; i++) {
              const currentPoint = polygonPoints[i];
              const nextPoint = polygonPoints[(i + 1) % polygonPoints.length];
              lineSegments += `${currentPoint.x} ${currentPoint.y} ${currentPoint.z}; ${nextPoint.x} ${nextPoint.y} ${nextPoint.z};`;
            }
            areaPolygon.setAttribute("line", lineSegments);
          }
        }
      });
    </script>
  </body>
</html>
